package com.ubs.training.server.dao.impl.jdbc;

import com.ubs.training.server.dao.TypeDao;
import com.ubs.training.server.dao.model.Type;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

import javax.sql.DataSource;
import java.util.Collections;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: xubuntu
 * Date: 8/21/12
 * Time: 4:44 AM
 * To change this template use File | Settings | File Templates.
 */
public class NamedParamTypeDaoImpl implements TypeDao {
    DataSource ds;

    NamedParameterJdbcOperations ops;


    public DataSource getDs() {
        return ds;
    }

    public void setDs(DataSource ds) {
        this.ds = ds;
        ops = new NamedParameterJdbcTemplate(ds);
    }

    @Override
    public List<Type> getAll() {
        return ops.query("select id, name from types", Collections.EMPTY_MAP, new BeanPropertyRowMapper(Type.class));
    }

    @Override
    public Type getById(int Id) {
        return ops.queryForObject("select id, name from types where id=:typeId", Collections.singletonMap("typeId", Id), new BeanPropertyRowMapper<Type>(Type.class));
    }

    @Override
    public boolean add(Type type) {
        int id = ops.queryForInt("select next value for cmstr_seq from dual", Collections.EMPTY_MAP);
        type.setId(id);
        return  ops.update("insert into types values (:id,:name)", new BeanPropertySqlParameterSource(type))>0;
    }

    @Override
    public boolean update(Type type) {
        int intoId = type.getId();
        Type oldType = ops.queryForObject("select id, name from types where id=:typeId", Collections.singletonMap("typeId", intoId), new BeanPropertyRowMapper<Type>(Type.class));
        if (!type.equals(oldType)) {
            return ops.update("update types set name=:name", new BeanPropertySqlParameterSource(type))>0;
        }
        return false;
    }

    @Override
    public boolean remove(Type type) {
        return  ops.update("delete from types where id=:id", new BeanPropertySqlParameterSource(type))>0;
    }
}
